package com.vision.bigDataApi.service.common.impl;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import com.vision.bigDataApi.config.ResultPool;
import com.vision.bigDataApi.enums.ReturnStatus;
import com.vision.bigDataApi.model.dto.Result;
import com.vision.bigDataApi.service.common.ResultService;
import com.vision.bigDataApi.utils.JsonUtilImpl;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 功能说明：返回结果接口实现
 * 创建时间：2018-4-8
 * 创建人：陈然
 * 备注：
 * 
 */
@Component
public class ResultServiceImpl implements ResultService {
	private static final Logger logger = LoggerFactory.getLogger(ResultService.class);
	@Autowired
	private JsonUtilImpl jsonUtil;
	@Autowired
	private ResultPool.ResultPoolWrap poolWrap;
	private GenericObjectPool<Result> pool;
	@PostConstruct
	public void init(){
		pool = poolWrap.getPool();
	}
	
	@PreDestroy
	public void destroy(){
		if(pool != null && !pool.isClosed()){
			pool.close();
		}
	}

	@Override
	public String result(ReturnStatus returnStatus, Object data, String msg,Long total) {
		Result result = null;
		try {
			result = pool.borrowObject();
		} catch (Exception e) {
			logger.debug("获取结果对象失败！");
			e.printStackTrace();
		}
		result.setStatus(returnStatus.getCode());
		result.setData(data);
		result.setMsg(msg);
		result.setTotal(total);
		logger.info(result.toString());
		String returnValue = jsonUtil.toJson(result);
		pool.returnObject(result);
		return returnValue;
	}
}
